/*
 *
 */
package org.jiscinvolve.astrodabis.barberry.common.core;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.jiscinvolve.astrodabis.barberry.common.core.Job;
import org.jiscinvolve.astrodabis.barberry.common.core.exception.ProcessingException;

/**
 *
 *
 */
public class JobRunner
implements Runnable
    {

    /**
     * Our debug logger.
     * 
     */
    private static Log log = LogFactory.getLog(JobRunner.class);

//    private static final int BATCH_SIZE = 50 ;
    private static final int BATCH_SIZE = 100 ;

    private Job.Parser parser ;
    public Job.Parser parser()
        {
        return this.parser;
        }
    public Job job()
        {
        return this.parser.job();
        }

    public JobRunner(Job.Parser parser)
        {
        this.parser = parser ;
        }

    public void run()
        {
        log.debug("JobRunner.run()");
        //
        // Process the iterator in batches.
        try {
            long start = System.currentTimeMillis();
            long count = 0 ;
            while (parser.hasNext())
                {
                log.debug("---- ----");
                count += batch();
                log.debug("---- ----");
                }
            long done = System.currentTimeMillis();
            long time = done - start ;
            long rate = (count * 1000) / time ;
            log.debug("Total done [" + count + "][" + time + "][" + rate + "]");
            }
        catch (ProcessingException ouch)
            {
            log.warn("Job ProcessingException [" + ouch.getMessage() + "]");
            }
        catch (Throwable ouch)
            {
            log.error("Unexpected exception during job processing [" + ouch.getClass() + "][" + ouch.getMessage() + "]");
            }
        }

    public long batch()
    throws ProcessingException
        {
        log.debug("JobRunner.batch()");

log.debug("Job.Factory.batch()");
log.debug("Job   [" + parser.job().ident() + "]");
log.debug("Size  [" + BATCH_SIZE + "]");

        long start = System.currentTimeMillis();

        long count = Womble.womble().jobs().batch(
            parser.job(),
            BATCH_SIZE,
            parser
            );                

        long done = System.currentTimeMillis();
        long time = done - start ;
        long rate = (count * 1000) / time ;
        log.debug("Done [" + count + "][" + time + "][" + rate + "]");
        return count ;
        }
    }

